package filter;

import entity.User;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "lf", urlPatterns = {"/shoppingcar.jsp"}, servletNames = {"atcs"})
public class LoginFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest hreq = (HttpServletRequest) request;
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf8");
        HttpSession session = hreq.getSession();
        User loginUser = (User) session.getAttribute("lu");

        if (loginUser == null) {
            //未登录，跳转到登录页面
            HttpServletResponse hresp = (HttpServletResponse) response;
            hresp.sendRedirect("login.html");
        } else {
            //已登录，继续进行下一环节
            chain.doFilter(request, response);
        }
    }
}
